﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Dapper;

namespace Analysis.DAL.Repositories
{
    public abstract class BaseRepository : IDisposable
    {
        private string connectionName = "Analysis";
        protected IDbConnection Connection { get; set; }
        private IDbTransaction Transaction { get; set; }
        private bool commited = false;
        protected Database db { get; set; }

        public BaseRepository()
        {
            var connStr = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            this.db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
            this.Connection = db.CreateConnection();
            this.Connection.Open();
        }

        public BaseRepository(Database db)
        {
            var connStr = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            this.db = db;
        }

        public void Commit()
        {
            if (!commited && Transaction != null)
            {
                Transaction.Commit();
                commited = true;
            }
        }

        public void Dispose()
        {
            if (!commited && Transaction != null)
            {
                Transaction.Commit();
            }

            if (Connection.State == ConnectionState.Open)
            {
                Connection.Close();
            }
        }

        
    }
}
